package com.hope.mychat.core;

import com.hope.mychat.domain.vo.Message;
import com.hope.mychat.support.WSMessageDecoder;
import com.hope.mychat.support.WSMessageEncoder;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;


/**
 * @author ZWH
 */

@ServerEndpoint(value = "/chat/{uid}", decoders = {WSMessageDecoder.class}, encoders = {WSMessageEncoder.class})
@Slf4j
public class ChatServerEndpoint {

    @OnOpen
    public void onOpen(@PathParam("uid") String uid, Session session) {
        // 将session放入到缓存中
        MyChat.LIVING_SESSIONS_CACHE.put(uid, session);
        // 在线人数+1
        MyChat.ONLINE_COUNT++;
        log.info("user {} online", uid);
    }

    @OnMessage
    public void onMessage(Message message) throws IOException, EncodeException {
        log.info("========================= message text");
        log.info(message.toString());
        MyChat.messageHandle(message);
    }

    @OnClose
    public void onClose(@PathParam("uid") String uid, Session session) {
        // 移除该用户session
        MyChat.LIVING_SESSIONS_CACHE.remove(uid);
        // 在线人数-1
        MyChat.ONLINE_COUNT--;
        try {
            session.close();
        } catch (IOException e) {
            log.error("websocket close msg: {}", e.getMessage());
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            log.error("websocket close msg: {}", e.getMessage());
        }
        log.error("websocket error msg: {}", throwable.getMessage());
    }
}
